/**
 * @description cookies
 * @author Zhangbin
 */
import Cookies from 'js-cookie'
import { UserInfoType, SettingKeyType } from '@/store/types'

// userinfo -> object type
export const getUserInfo = (key: string): UserInfoType => {
  try {
    // 断言string
    return JSON.parse(Cookies.get(key) as string)
  } catch (error) {
    return { token: '', id: '' }
  }
}

export const setUserInfo = (key: string, value: object, exp: number = 1): void => {
  Cookies.set(key, JSON.stringify(value), { expires: exp })
}
//

// setting
export const setSettings = (key: string, value: SettingKeyType, exp: number = 1): void => {
  Cookies.set(key, JSON.stringify(value), { expires: exp })
}
export const getSettings = (key: string): object => {
  try {
    // 断言
    return JSON.parse(Cookies.get(key) as string)
  } catch (error) {
    return {}
  }
}
//

// remove all cookies
export const clearCookies = (): void => {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
  if (keys) {
    for (var i = keys.length; i--;)
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
  }
}
//

